<template>
  <div class="gyk-common-table">
    <!-- 表格 -->
    <div class="gyk-table-container">
      <el-table :data="tableData" :height="tableHeight" :max-height="tableMaxHeight" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column v-if="selectable" prop="el_table_column_selection" type="selection" width="55" align="center" />
        <el-table-column v-if="showIndex" type="index" label="序号" width="80" prop="el_table_column_index"
          align="center" />
        <el-table-column v-for="item in tableColumns" :key="item.prop" :fixed="item.fixed" :prop="item.prop" :label="item.label"
          :width="item.width" :align="item.align">
          <template #default="scope">
            <!-- 自定义的列 -->
            <table-slot v-if="item.render" :render="item.render" :row="scope.row" :index="scope.$index" :column="item" />
            <!-- 默认展示字符串 -->
            <span v-else>{{ getLabelByProp(scope.row, item.prop) }}</span>
          </template>
        </el-table-column>

      </el-table>
    </div>

    <!-- 分页 -->
    <div class="gyk-pagination-container">
      <Pagination v-show="tableTotal > 0" :total="tableTotal" :page.sync="pageForm.pageNo" :limit.sync="pageForm.pageSize"
        @pagination="getList" />
    </div>


  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import TableSlot from './TableSlot.vue'
import Pagination from '../Pagination/index.vue'

const defProps = withDefaults(defineProps<{
  // 表格数据
  tableData: any[],
  // 表格高度
  tableHeight: string,
  // 表格最大高度
  tableMaxHeight: string,
  // 表格总数据量
  tableTotal: number,
  // 分页查询条件
  pageForm: {
    pageNo: number,
    pageSize: number,
  },
  // 表格分页组件的位置
  paginationPosition: string
  // 是否显示选中按钮
  selectable: boolean,
  // 是否显示索引
  showIndex: boolean,
  // 显示表格列
  tableColumns: any[]
}>(), {
  tableData: () => [],
  tableHeight: '100%',
  tableMaxHeight: '100%',
  tableTotal: 0,
  tableLimit: 10,
  pageForm: () => {
    return {
      pageNo: 1,
      pageSize: 10
    }
  },
  paginationPosition: 'flex-end',
  selectable: false,
  showIndex: false,
  tableColumns: () => []
})

const emits = defineEmits<{
  (e: 'pagination', data: { pageNo: number, pageSize: number }): void,
  (e: 'selection-change', selection: any): void,
}>()

const getList = (data) => {
  emits('pagination', data)
}

const handleSelectionChange = (selection) => {
  emits('selection-change', selection)
}

// 如果属性值带了.，则说明数据包裹了多层，需要层层获取
const getLabelByProp = (row, prop) => {
  let ret = row
  if (prop.indexOf(".") > -1) {
    const props = prop.split(".")
    for (const i in props) {
      ret = ret[props[i]]  
    }
  }else {
    ret = ret[prop]
  }
  return ret
}

</script>

<style lang="scss" scoped>
@include b(common-table) {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  @include bfc;

  @include b(table-container) {
    flex: 1;
    width: 100%;
  }

  @include b(pagination-container) {}

}
</style>